<template>
  <el-pagination
    background
    layout="prev, pager, next"
    v-model:currentPage="pagerState.pagerIndex"
    :total="pagerState.count">
  </el-pagination>
</template>

<script setup lang="ts">

  import {
    watch,
    onBeforeUnmount,
    toRefs, // 卸载前被调用
  } from 'vue'

  // 获取父组件的状态
  import { getListState } from '../state/list'

  const { name } = defineProps({name: String})
  // const props = defineProps({name: String})
  // const { name } = toRefs(props)

  console.log(name)

  watch (() => name, (val) => {
    console.log('直接监听 name ：', val)
  })
  
  const foo1 = (v: any) => {
    // 函数内部监听传入的参数
    watch (() => v, (val) => {
      console.log('函数内部监听 name：', val)
    })
  }

  foo1(name)

  // --------------

  const { pagerState }  = getListState()

  // console.log('state\n', pagerState)

  const keyInfo = {
    ctrl: false,
    keyCode: 1
  }

  // 通过键盘翻页
  const setPager = (pagerState, keyInfo) => {
    const code = keyInfo.keyCode

    if (code >= 49 && code <= 57) {
        // 主键盘区 1 - 9
        pagerState.pagerIndex = code - 48
      } else if (code >= 97 && code <= 105) {
        // 小键盘 1 - 9
        pagerState.pagerIndex = code - 96
      } else if (code === 48) {
        // 主键盘区 0
        pagerState.pagerIndex = 10
      } else if (code === 96) {
        // 小键盘 0
        pagerState.pagerIndex = 10
      } else if (code === 36) {
        // home， 首页
        pagerState.pagerIndex = 1
      } else if (code === 35) {
        // end， 末页
        pagerState.pagerIndex = 1000000
      } else if (code === 33) {
        // pageUp， 上一页
        pagerState.pagerIndex -= 1
      } else if (code === 34) {
        // pageDown， 下一页
        pagerState.pagerIndex += 1
      }
  }

  window.onkeydown = (e: Event) => {
    // target srcElement
    if (e.target?.localName === 'body') {
      console.log('onkeydown', e)
      keyInfo.keyCode = e.keyCode
      setPager(pagerState, keyInfo)

    }

  }

  onBeforeUnmount(() => {
    console.log('分页组件被卸载！')
  }) 
</script>